package com.anniljing.kotlionlearn.Basic.classes

import kotlin.properties.Delegates

fun main() {
    UniversalDB(sqlDB()).save()
    UniversalDB(GreenDaoDB()).save()

    val delegation = DelegationProperties()
    delegation.count = 20
    println(delegation.total)

    val delegationLazyPropers = DelegationLazyPropers()
    println(delegationLazyPropers.lazyValue)
    println(delegationLazyPropers.lazyValue)

    val delegationObserver = DelegationObserver()
    delegationObserver.name = "you"
    delegationObserver.name = "me"

    val delegationByMap = DelegationByMap(mapOf("name" to "Hello", "age" to 18))
    println("My name is ${delegationByMap.name},i am ${delegationByMap.age} years old")
}

interface DB {
    fun save()
}

class sqlDB : DB {
    override fun save() {
        println("save to sql")
    }
}

class GreenDaoDB : DB {
    override fun save() {
        println("save to greenDao")
    }
}

/**
 * Kotlin“委托类”委托的是接口方法
 */
class UniversalDB(db: DB) : DB by db

/**
 * 委托属性”委托的，则是属性的 getter、setter
 */
class DelegationProperties {
    var count: Int = 0
    var total: Int by ::count
}

/**
 * 懒加载委托，顾名思义，就是对于一些需要消耗计算机资源的操作，我们希望它在被访问的时候才去触发，从而避免不必要的资源开销
 */
class DelegationLazyPropers {
    val lazyValue: String by lazy {
        println("computed")
        "Hello"
    }
}

class DelegationObserver {
    var name: String by Delegates.observable("NULL",
        { property, oldValue, newValue -> println("old:$oldValue,new:$newValue") })
}

class DelegationByMap(val map: Map<String, Any?>) {
    val name: String by map
    val age: Int by map
}